package com.green.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.green.common.Constant;
import com.green.common.util.SessionPerson;
import com.green.common.util.StringUtil;
import com.green.model.manage.Org;
import com.green.model.manage.Person;
import com.green.service.common.ServiceContext;
import com.green.service.manage.OrgService;
import com.green.service.manage.PersonService;
import com.green.web.util.PermissionHelper;

/**
 * 基本的控制器
 *
 */
public class BaseController{
	@Autowired
	private PersonService personService;
	@Autowired
	private OrgService orgService;
	public static final String PAGINATIONKEY = "pagination";// 分页实体key名
	public static final String USERKEY = "user";// 当前用户key
    public static final String ITEM="item";//如果是一个实体的时候一半用这个key
    public static final String ITEMS="items";//如果是一个集合的时候一半用这个key
	public HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
	}

	public HttpSession getSession() {
		return ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest().getSession();
	}

	public ServletContext getServletContext() {
		return ContextLoader.getCurrentWebApplicationContext()
				.getServletContext();
	}

	public int getInt(String name) {
		return getInt(name, 0);
	}

	public int getInt(String name, int defaultValue) {
		String resultStr = getRequest().getParameter(name);
		if (resultStr != null) {
			try {
				return Integer.parseInt(resultStr);
			} catch (Exception e) {
				return defaultValue;
			}
		}
		return defaultValue;
	}

	public BigDecimal getBigDecimal(String name) {
		return getBigDecimal(name, null);
	}

	public BigDecimal getBigDecimal(String name, BigDecimal defaultValue) {
		String resultStr = getRequest().getParameter(name);
		if (resultStr != null) {
			try {
				return BigDecimal.valueOf(Double.parseDouble(resultStr));
			} catch (Exception e) {
				return defaultValue;
			}
		}
		return defaultValue;
	}

	public String getString(String name) {
		return getString(name, null);
	}

	public String getString(String name, String defaultValue) {
		String resultStr = getRequest().getParameter(name);
		if (resultStr == null || "".equals(resultStr)
				|| "null".equals(resultStr) || "undefined".equals(resultStr)) {
			return defaultValue;
		} else {
			return resultStr.trim();
		}
	}

	/**
	 * 发送消息 ajax用
	 * 
	 * @param response
	 * @param result
	 */
	public void outPrint(HttpServletResponse response, Object result) {
		try {
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.print(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	/**
	 * 取当前登录用户信息 modified by taking.wang reason:因为现在没有User对象
	 * 
	 * @return
	 */
	public Person getCurrentUser() {
		Person currentPerson = SessionPerson.get();
		return currentPerson;
	}

	/**
	 * 得到内置对象中的值
	 * 
	 * @param <T>
	 * @param key
	 * @param scop
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T getBean(String key, String scop) {
		HttpServletRequest req = this.getRequest();
		T t = null;
		if (null == scop) {
			t = (T) req.getAttribute(key);
			if (null == t)
				t = (T) req.getSession().getAttribute(key);
			if (null == t)
				t = (T) getServletContext().getAttribute(key);
		} else {

			if ("request".equals(scop)) {
				t = (T) req.getAttribute(key);
			} else if ("session".equals(scop)) {
				t = (T) req.getSession().getAttribute(key);
			} else if ("application".equals(scop)) {
				t = (T) getServletContext().getAttribute(key);
			}
		}
		return t;
	}

	/**
	 * 放入内置对象
	 * 
	 * @param key
	 * @param obj
	 * @param scop
	 */
	public void setBean(String key, Object obj, String scop) {
		if (null == key) {
			key = "request";
		}
		HttpServletRequest req = this.getRequest();
		if ("request".equals(scop)) {
			req.setAttribute(key, obj);
		} else if ("session".equals(scop)) {
			req.getSession().setAttribute(key, obj);
		} else if ("application".equals(scop)) {
			this.getServletContext().setAttribute(key, obj);
		}
	}

	/**
	 * 把obj 放入map
	 * 
	 * @param map
	 * @param key
	 * @param obj
	 * @param isInsertDefaultAdd
	 *            是不是插入默认数据
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void setFreeMarkerMap(Map map, String key, Object obj,
			boolean isInsertDefaultAdd) {
		if (true == isInsertDefaultAdd) {
			setDefaultDate(map);
		}
		map.put(key, obj);
	}

	

	/**
	 * 插入默认的数据
	 * 
	 * @param map
	 */
	@SuppressWarnings({ "static-access", "unchecked", "rawtypes" })
	private void setDefaultDate(Map map) {
		map.put(this.USERKEY, this.getSession().getAttribute(this.USERKEY));// 加入用户
	}
	
	public String getOwners() {
        StringBuffer sb = new StringBuffer();
        String orgIds = PermissionHelper.getOrgIdsStr();
        if(StringUtil.isNotEmpty(orgIds)){
            Map<String,Object> param = new HashMap<String, Object>();
            param.put("orgIds", orgIds);
            List<Person> persons = personService.getPersonList(param);
            if(persons.size()>0){
                for(Person p:persons){
                    sb.append("'");
                    sb.append(p.getId());
                    sb.append("',");
                }
            }
        }
        Person person = ServiceContext.getLoginPerson();
        sb.append("'").append(person.getId()).append("'");
        String onwers = sb.toString();
        return onwers;
    }
	
	protected boolean isJoingreen(){
		Org org=orgService.getOrgById(ServiceContext.getLoginPerson().getControUnit().getId());
		if(org.getId().equals(Constant.JOIN_ID)){
    		return true;
    	}else{
    		return false;
    	}
	}
}
